package com.yhp.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.system.comm.util.JsonUtils;
import com.system.comm.util.Snowflake;
import com.system.common.pojo.BisBagProject;
import com.system.common.pojo.BisNurseBag;
import com.system.common.pojo.BisNurseProject;
import com.system.common.pojo.BisNurseType;
import com.system.common.pojo.SysUser;
import com.yhp.service.BisNurseBagService;
import com.yhp.service.BisNurseProjectService;
import com.yhp.service.BisNurseTypeService;

@Controller
@RequestMapping("bnb")
public class BisNurseBagController {
	@Autowired
	private BisNurseBagService bagService;
	@Autowired
	private BisNurseProjectService projectService;
	@Autowired
	private BisNurseTypeService typeService;

	/**
	 * 礼包>>>>>>列表显示所有
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("bag")
	public String bag(Model model, HttpServletRequest request) {
		Map<String, Object> map = initMap(request);
		List<BisNurseBag> bisNurseBagList = bagService.selectByExample(map);
		model.addAttribute("bisNurseBagList", bisNurseBagList);

		List<BisNurseType> listType = typeService.selectByExample();
		model.addAttribute("listType", listType);
		return "bis_nurse/bag";
	}

	public Map<String, Object> initMap(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		String bagId = request.getParameter("bagId");
		String bagName = request.getParameter("bagName");
		String status = request.getParameter("status");
		if (bagId != null && !bagId.trim().equals("")) {
			map.put("bagId", bagId);
		}
		if (bagName != null && !bagName.trim().equals("")) {
			map.put("bagName", bagName);
		}
		if (status != null && !status.trim().equals("")) {
			map.put("status", status);
		}
		return map;
	}

	/**
	 * 礼包>>>>>>详情
	 * 
	 * @param bagId
	 * @param model
	 * @return
	 */
	@RequestMapping("bag_details")
	public String bag_details(String bagId, Model model) {
		BisNurseBag bisNurseBag = bagService.selectByPrimaryKey(bagId);
		if (bisNurseBag != null) {
			model.addAttribute("bisNurseBag", bisNurseBag);
		}

		Map<String, Object> map = new HashMap<>();
		map.put("bagId", bagId);
		List<BisBagProject> bisBagProject = bagService.selectByBagId(map);
		if (bisBagProject != null && bisBagProject.size() != 0) {
			model.addAttribute("bisBagProject", bisBagProject);
		}
		return "bis_nurse/bag_details";
	}

	/**
	 * 礼包>>>>>>点击添加护理项目
	 * 
	 * @return
	 */
	@RequestMapping(value = "bag_project_list", produces = "application/json;charset=utf-8")
	@ResponseBody
	public String bag_project_list(String projectId, String projectName, String typeId) {
		Map<String, Object> map = new HashMap<>();
		if (projectId != null) {
			map.put("projectId", projectId);
		}
		if (projectName != null) {
			map.put("projectName", projectName);
		}
		if (typeId != null) {
			map.put("typeId", typeId);
		}
		List<BisNurseProject> ProjectList = projectService.selectByExample(map);
		List<BisNurseProject> bisNurseProjects=new ArrayList<>();
		for (BisNurseProject bisNurseProject : ProjectList) {
			if (bisNurseProject.getIsDel().equals("0")&&bisNurseProject.getStatus().equals("1")) {
				BisNurseType bisNurseType = typeService.selectByPrimaryKey(bisNurseProject.getTypeId());
				bisNurseProject.setTypeName(bisNurseType.getTypeName());
				bisNurseProjects.add(bisNurseProject);
			}
		}
		String ProjectLists = JsonUtils.toJson(bisNurseProjects);
		return ProjectLists;
	}

	/**
	 * 礼包>>>>>>添加
	 * 
	 * @return
	 */
	@RequestMapping("bag_add")
	public String bag_add(BisNurseBag bisNurseBag,String projectNum, String projectId, String projectNewPrice,
			HttpSession session, @RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
		// 卡剩量 是否删除 创建时间 创建用户编号 修改时间 修改用户编号
		SysUser user = (SysUser) session.getAttribute("user");
		Snowflake sf = new Snowflake(0, 0);
		bisNurseBag.setBagId(sf.nextId() + "");
		file(files, request, bisNurseBag);
		bisNurseBag.setIsDel("0");
		bisNurseBag.setCreateTime(new Date());
		bisNurseBag.setCreateUserId(user.getUserId());
		bisNurseBag.setRemainNum(bisNurseBag.getOpenCardNum());

		String[] projectNums = projectNum.split(",");
		String[] projectIds = projectId.split(",");
		String[] projectNewPrices = projectNewPrice.split(",");
		for (int i = 0; i < projectIds.length; i++) {
			BisBagProject bagProject = new BisBagProject();
			bagProject.setBagId(bisNurseBag.getBagId());
			bagProject.setProjectId(projectIds[i]);
			BisNurseProject bisNurseProject = projectService.selectByPrimaryKey(projectIds[i]);
			bagProject.setProjectOldPrice(bisNurseProject.getRmbPrice());
			bagProject.setProjectNewPrice(Double.parseDouble(projectNewPrices[i]));
			bagProject.setProjectNum(Integer.parseInt(projectNums[i]));
			bagProject.setCreateTime(new Date());
			bagProject.setCreateUserId(user.getUserId());
			bagService.insert(bagProject);
		}
		bisNurseBag.setRemainNum(bisNurseBag.getOpenCardNum());
		bagService.insert(bisNurseBag);
		return "redirect:/bnb/bag";
	}

	/**
	 * 礼包 删除
	 * 
	 * @param bagId
	 * @return
	 */
	@RequestMapping("bag_del")
	public String bag_del(String bagId) {
		BisNurseBag selectByPrimaryKey = bagService.selectByPrimaryKey(bagId.substring(0, bagId.length() - 1));
		selectByPrimaryKey.setIsDel("1");
		bagService.updateByPrimaryKey(selectByPrimaryKey);
		return "redirect:/bnb/bag";
	}

	/**
	 * 礼包 修改赋值
	 * 
	 * @param bagId
	 * @return
	 */
	@RequestMapping(value = "bagByBagId", produces = "application/json;charset=utf-8")
	@ResponseBody
	public String bagByBagId(String bagId) {
		List<BisBagProject> bagProject = bagService.selectByBagId(bagId);
		return JsonUtils.toJson(bagProject);
	}

	/**
	 * 礼包 修改
	 * 
	 * @param bisNurseBag
	 * @param projectNum
	 * @param projectId
	 * @param projectNewPrice
	 * @param session
	 * @return
	 */
	@RequestMapping("bag_update")
	public String bag_update(BisNurseBag bisNurseBag, String projectNum, String projectId, String projectNewPrice,
			HttpSession session, @RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
		String[] projectNums = projectNum.split(",");// 项目数量
		String[] projectIds = projectId.split(",");// 项目编号
		String[] projectNewPrices = projectNewPrice.split(",");// 礼包价格
		// 修改礼包表
		// 卡剩量 是否删除 创建时间 创建用户编号 修改时间 修改用户编号
		SysUser user = (SysUser) session.getAttribute("user");
		file(files, request, bisNurseBag);
		bisNurseBag.setIsDel("0");
		BisNurseBag primaryKey = bagService.selectByPrimaryKey(bisNurseBag.getBagId());
		bisNurseBag.setCreateTime(primaryKey.getCreateTime());
		bisNurseBag.setModifyTime(new Date());
		bisNurseBag.setCreateUserId(primaryKey.getCreateUserId());
		bisNurseBag.setModifyUserId(user.getUserId());
		bisNurseBag.setRemainNum(primaryKey.getRemainNum());
		// 修改礼包和项目的桥表
		// 先删除
		bagService.deleteByBagId(bisNurseBag.getBagId());
		// 再重新添加
		for (int i = 0; i < projectIds.length; i++) {
			BisBagProject bagProject = new BisBagProject();
			bagProject.setBagId(bisNurseBag.getBagId());// 礼包编号
			bagProject.setProjectId(projectIds[i]);// 项目编号
			BisNurseProject selectByPrimaryKey = projectService.selectByPrimaryKey(projectIds[i]);
			bagProject.setProjectOldPrice(selectByPrimaryKey.getRmbPrice());// 项目原价
			bagProject.setProjectNewPrice(Double.parseDouble(projectNewPrices[i]));// 项目活动价
			bagProject.setProjectNum(Integer.parseInt(projectNums[i]));// 项目数量
			bagProject.setCreateTime(new Date());// 创建时间
			bagProject.setCreateUserId(user.getUserId());// 用户编号
			// 修改桥表
			bagService.insert(bagProject);
		}
		// 修改礼包表
		bagService.updateByPrimaryKey(bisNurseBag);
		return "redirect:/bnb/bag";
	}

	/**
	 * 文件上传
	 * 
	 * @param files
	 * @param request
	 * @param bisNurseProject
	 */
	public void file(MultipartFile[] files, HttpServletRequest request, BisNurseBag bisNurseBag) {
		if (files != null && files.length > 0) {// 判断file数组不能为空并且长度大于0
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			if (files[0].getOriginalFilename() != null && !files[0].getOriginalFilename().equals("")) {
				@SuppressWarnings("deprecation")
				String path = request.getRealPath("/upload/coverPhoto");// 获取项目的路径
				path = path + "/" + sdf.format(new Date());// 存放图片的路径
				File file2 = new File(path);
				if (!file2.exists()) {// 如果当前项目不存在
					file2.mkdirs();// 创建一个新的空目录
				}
				String fileName1 = files[0].getOriginalFilename();// 获取文件名
				File file3 = new File(path, fileName1);// 第一个参数表示第二个参数所在的路径
				if (!file3.exists()) {// 如果当前项目不存在
					try {
						file3.createNewFile();// 创 建一个空的目录
						files[0].transferTo(file3);// 将上传的文件内容拷贝到新文件中
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				bisNurseBag.setCoverPhoto("/upload/coverPhoto/" + sdf.format(new Date()) + "/" + fileName1);
			}

			if (files[1].getOriginalFilename() != null && !files[1].getOriginalFilename().equals("")) {
				@SuppressWarnings("deprecation")
				String path1 = request.getRealPath("/upload/coverBigPhoto");// 获取项目的路径
				path1 = path1 + "/" + sdf.format(new Date());// 存放图片的路径
				File file5 = new File(path1);
				if (!file5.exists()) {// 如果当前项目不存在
					file5.mkdirs();// 创建一个新的空目录
				}
				String fileName2 = files[1].getOriginalFilename();
				File file4 = new File(path1, fileName2);// 第一个参数表示第二个参数所在的路径
				if (!file4.exists()) {// 如果当前项目不存在
					try {
						file4.createNewFile();// 创 建一个空的目录
						files[1].transferTo(file4);// 将上传的文件内容拷贝到新文件中
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				bisNurseBag.setCoverBigPhoto("/upload/coverBigPhoto/" + sdf.format(new Date()) + "/" + fileName2);
			}
		}
	}
}